<?php

function url_for($ref, $params= array())
{
  global $routes;
  if (array_key_exists($ref, $routes))
  {
    $url = $routes[$ref]['url'];

    foreach ($params as $key => $value)
    {
      if (!Validator::getValidator('array', $value))
        $url = str_replace(':' . $key, Rewrite::formatUrlRw($value), $url);
    }

    return $url;
  }
  else
  {
    return false;
  }
}

function go($ref, $params= array())
{
  global $routes;
  if (array_key_exists($ref, $routes))
  {
    $url = $routes[$ref]['url'];

    foreach ($params as $key => $value)
    {
      if (!Validator::getValidator('array', $value))
        $url = str_replace(':' . $key, Rewrite::formatUrlRw($value), $url);
    }

    header('location:' . $url);
    exit();
  }
  else
  {
    return false;
  }
}

function sort_url_for($ref, $params=array())
{
  return url_for($ref, array('champ' => Rewrite::formatUrlRw($params['champ']),
      'tri' => Rewrite::formatUrlRw((array_key_exists('tri', $params)) ?
                      ($params['tri'] == 'asc') ? ('desc') : ('asc') : 'asc'),
      'page' => 1));
}

function get_url()
{
  $request = $_SERVER['REQUEST_URI'];
  $pos = strpos($request, '?');
  if ($pos)
    $request = substr($request, 0, $pos);

  return $request;
}

function url_selected_for($ref, $style, $urlRef='')
{
  global $routes;

  foreach ($routes as $reference => $value)
  {
    if ($value['url'] == get_url())
    {
      //echo $ref.'::'.$reference;
      if ($ref == $reference)
        return $style;
    }
    else
    {
      if ($value['url'] == $urlRef)
      {
        //echo $ref.'::'.$reference;
        if ($ref == $reference)
          return $style;
      }
    }
  }
}
